const axios = require('axios');

// 配置
const BASE_URL = 'http://localhost:3000/api';
const JWT_TOKEN = 'your_jwt_token_here'; // 替换为实际的JWT token

// 设置请求头
const headers = {
  'Authorization': `Bearer ${JWT_TOKEN}`,
  'Content-Type': 'application/json'
};

// 测试已购买章节的积分显示
async function testPurchasedChaptersPoints() {
  try {
    console.log('🚀 开始测试已购买章节的积分显示...\n');
    
    if (JWT_TOKEN === 'your_jwt_token_here') {
      console.log('⚠️  请先设置有效的JWT token');
      console.log('   在脚本中修改 JWT_TOKEN 变量的值\n');
      return;
    }

    const shortsId = 1;
    const chapterId = 2;

    // 1. 先查看短剧详情，检查初始积分
    console.log('1️⃣ 查看短剧详情（初始状态）...');
    try {
      const detailResponse = await axios.get(
        `${BASE_URL}/shorts/${shortsId}`,
        { headers }
      );
      
      console.log('✅ 获取短剧详情成功');
      const shortData = detailResponse.data;
      console.log(`📺 短剧标题: ${shortData.title}`);
      console.log(`📖 章节数量: ${shortData.chapters.length}`);
      
      // 显示所有章节的积分
      shortData.chapters.forEach((chapter, index) => {
        console.log(`   章节${index + 1}: ${chapter.title} - 积分: ${chapter.points}`);
      });
      
    } catch (error) {
      console.log('❌ 获取短剧详情失败:', error.response?.data?.message || error.message);
      return;
    }

    console.log('\n' + '─'.repeat(50));

    // 2. 购买指定章节
    console.log('2️⃣ 购买指定章节...');
    try {
      const orderResponse = await axios.post(
        `${BASE_URL}/shorts/order`,
        {
          shortsId: shortsId,
          chapterIds: [chapterId]
        },
        { headers }
      );
      
      console.log('✅ 购买章节成功:', JSON.stringify(orderResponse.data, null, 2));
      
      const orderData = orderResponse.data;
      console.log(`💎 总积分: ${orderData.totalPoints}`);
      console.log(`📋 订单数量: ${orderData.orders.length}`);
      console.log(`👑 VIP用户: ${orderData.isVip ? '是' : '否'}`);
      
    } catch (error) {
      console.log('❌ 购买章节失败:', error.response?.data?.message || error.message);
      
      if (error.response?.status === 400) {
        console.log('💡 提示: 可能该章节已购买');
      } else if (error.response?.status === 403) {
        console.log('💡 提示: 积分不足');
        return;
      }
    }

    console.log('\n' + '─'.repeat(50));

    // 3. 再次查看短剧详情，检查积分变化
    console.log('3️⃣ 再次查看短剧详情（购买后）...');
    try {
      const detailResponse2 = await axios.get(
        `${BASE_URL}/shorts/${shortsId}`,
        { headers }
      );
      
      console.log('✅ 获取短剧详情成功');
      const shortData2 = detailResponse2.data;
      console.log(`📺 短剧标题: ${shortData2.title}`);
      console.log(`📖 章节数量: ${shortData2.chapters.length}`);
      
      // 显示所有章节的积分，特别标注已购买的章节
      shortData2.chapters.forEach((chapter, index) => {
        const isPurchased = chapter.points === 0 && chapter.id === chapterId;
        const status = isPurchased ? '✅ 已购买' : '💰 未购买';
        console.log(`   章节${index + 1}: ${chapter.title} - 积分: ${chapter.points} ${status}`);
      });
      
    } catch (error) {
      console.log('❌ 获取短剧详情失败:', error.response?.data?.message || error.message);
    }

    console.log('\n' + '─'.repeat(50));

    // 4. 测试随机短剧接口的积分显示
    console.log('4️⃣ 测试随机短剧接口的积分显示...');
    try {
      const randomResponse = await axios.get(
        `${BASE_URL}/shorts/random?count=3`,
        { headers }
      );
      
      console.log('✅ 获取随机短剧成功');
      const randomData = randomResponse.data;
      
      randomData.forEach((short, shortIndex) => {
        console.log(`\n短剧${shortIndex + 1}: ${short.title}`);
        console.log(`章节数量: ${short.chapters.length}`);
        
        short.chapters.forEach((chapter, chapterIndex) => {
          const isPurchased = chapter.points === 0 && short.id === shortsId && chapter.id === chapterId;
          const status = isPurchased ? '✅ 已购买' : '💰 未购买';
          console.log(`  章节${chapterIndex + 1}: ${chapter.title} - 积分: ${chapter.points} ${status}`);
        });
      });
      
    } catch (error) {
      console.log('❌ 获取随机短剧失败:', error.response?.data?.message || error.message);
    }

    console.log('\n✨ 已购买章节积分显示测试完成！');
    console.log('\n💡 测试要点:');
    console.log('   - 购买章节前，章节显示原积分');
    console.log('   - 购买章节后，该章节积分变为0');
    console.log('   - 短剧详情和随机短剧接口都显示正确的积分');
    console.log('   - VIP用户和已购买用户都享受0积分优惠');

  } catch (error) {
    console.error('❌ 测试过程中发生错误:', error.message);
  }
}

// 运行测试
testPurchasedChaptersPoints().catch(console.error); 